package cn.mlong.demo.convert

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.ui.Messages

class HexConvertAction : AnAction("Hex/Dec转换") {

    override fun actionPerformed(e: AnActionEvent) {
        val editor = e.getRequiredData(CommonDataKeys.EDITOR)
        val project = e.getRequiredData(CommonDataKeys.PROJECT)
        val selectedText = editor.selectionModel.selectedText ?: return

        val options = arrayOf("10 → 16", "16 → 10", "取消")
        val choice = Messages.showDialog(
            project,
            "选择转换方向",
            "进制转换",
            options,
            0,
            Messages.getQuestionIcon()
        )

        val converted = when (choice) {
            0 -> HexConverter.f10to16(selectedText)
            1 -> HexConverter.f16to10(selectedText)
            else -> return
        }

        //替换
        //        WriteCommandAction.runWriteCommandAction(project) {
        //            editor.document.replaceString(
        //                editor.selectionModel.selectionStart,
        //                editor.selectionModel.selectionEnd,
        //                converted
        //            )
        //        }
        //只是显示
        Messages.showMessageDialog(
            project,
            """
            原始值: $selectedText
            转换结果: $converted
            """.trimIndent(),
            "转换结果",
            Messages.getInformationIcon()
        )
    }

    override fun update(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR)
        e.presentation.isEnabledAndVisible = editor?.selectionModel?.hasSelection() ?: false
    }
}